import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import indexAdminRoute from "@/tool/adminRoute";
import { notification } from "ant-design-vue";
Vue.use(Router);

let router = new Router({
  base: process.env.BASE_URL,
  routes: [
    { path: "/", redirect: "/admin" },
    {
      path: "/admin",
      name: "admin",
      component: () => import("@/views/index.vue"),
      redirect: "/admin/login",
      children: [
        {
          path: "login",
          name: "adminLogin",
          component: () => import("@/views/login/index.vue")
        },
        indexAdminRoute
      ]
    },
    {
      path: "*",
      name: "notFound",
      component: () => import("@/views/notFound/index.vue")
    }
  ]
});
export default router;

router.beforeEach(function(to, from, next) {
  if (to.matched[1].name === "adminIndex") {
    // 只在刷新的时候获取sessionStorage的state
    if (from.matched.length === 0) {
      let aState = window.sessionStorage.getItem("aState");
      if (aState) {
        store.replaceState(JSON.parse(aState));
      }
    }
  }
  if (to.matched.some(record => record.meta.isLogin)) {
    // 判断该路由是否需要登录权限
    let token = window.localStorage.getItem("token");
    if (token) {
      // 获取当前的token是否存在
      next();
    } else {
      notification.warning({
        message: "请您先登录账号！"
      });
      next({
        path: "/admin/login"
      });
    }
  } else {
    next();
  }
});
